package com.cyy.view

import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.CharsetUtil
import cn.hutool.core.util.ReflectUtil
import cn.hutool.setting.Setting
import com.cyy.app.Styles
import com.cyy.controller.CyyGenerator
import com.cyy.model.Constants
import com.cyy.model.GmodelModel
import com.cyy.srv.GenSrv
import com.jfinal.kit.Kv
import com.jfinal.kit.StrKit
import com.jfinal.plugin.activerecord.Config
import com.jfinal.plugin.activerecord.Db
import com.jfinal.plugin.activerecord.DbKit
import com.jfinal.plugin.activerecord.DbPro
import com.jfinal.plugin.activerecord.dialect.Dialect
import com.jfinal.plugin.activerecord.generator.TypeMapping
import com.jfinal.template.EngineConfig
import javafx.geometry.Orientation
import javafx.scene.control.ListView
import javafx.scene.control.TextFormatter
import tornadofx.*
import java.util.*
import javax.sql.DataSource

class TopView(val gmodel: GmodelModel, val genSrv: GenSrv) : View("My View") {
    val engine = gmodel.engine.value
    var tbls = gmodel.tables
    lateinit var gen: CyyGenerator
    // 限定textfield输入值
    val FirstTenFilter: (TextFormatter.Change) -> Boolean = { change ->
        !change.isAdded || change.controlNewText.let {
            it.isInt() && it.toInt() in 0..65535
        }
    }

    override val root = titledpane("数据库设置") {
        hbox(5) {
            form {
                fieldset(labelPosition = Orientation.VERTICAL) {
                    hbox(10) {
                        field("主机地址") {
                            textfield(gmodel.host) {
                                addClass(Styles.txt100)
                                text = "localhost"
                                required(message = "Enter host for your database")
                            }
                        }
                        field("主机端口") {
                            textfield(gmodel.port) {
                                addClass(Styles.txt100)
                                text = "3306"
                                filterInput(FirstTenFilter)
                                required(message = "Enter port for your database")
                            }
                        }
                        field("用户名") {
                            textfield(gmodel.user) {
                                addClass(Styles.txt100)
                                text = "root"
                                required(message = "Enter user name for your database")
                            }
                        }
                        field("密码") {
                            textfield(gmodel.pwd) {
                                addClass(Styles.txt100)
                                text = "root"
                                required(message = "Enter user name for your database")
                            }
                        }
                        field{
                            vbox(10) {
                                button("测试连接") {
                                    action {
                                        if ((gmodel.arp.value != null)) {
//                    Constants.closeDb(gmodel.dataSource.value)
                                            gmodel.arp.value.stop()
                                        }
                                        // 每次点击"测试连接"测试连接时，都将之前保存的db和table列表清空
                                        gmodel.dbs.clear()
                                        gmodel.tables.clear()
                                        if (testDb2().not()) return@action
                                    }
                                }
                                button("Generate") {
                                    //            enableWhen(gmodel.dbOK)
//            enableWhen(booleanProperty(false))

//            action {
//                try {
//                    val btp = gmodel.baseTemplatePath.value
//                    val a = arrayListOf<String>()
//                    val aa = arrayListOf<String>()
//                    val c = gmodel.removedTableNamePrefixes.value.split(",")
////                    a.add("ay_")
////                    a.add("Ay_")
//                    a.addAll(c)
//                    val b = a.toTypedArray()
//                    aa.addAll(gmodel.excludedTable)
//                    val bb = aa.toTypedArray()
//                    gmodel.metaBuilder.value.setRemovedTableNamePrefixes(*b)
//                    gmodel.metaBuilder.value.addExcludedTable(*bb)
//                    gmodel.metaBuilder.value.setTypeMapping(TypeMapping())
//
//                    engine.setBaseTemplatePath(btp)
//                    gen = CyyGenerator(gmodel.dataSource.value, engine, gmodel.metaBuilder.value, btp)
//
////                    val sett = getSetting(gmodel.settingFile.value)
////                    val kv = Kv().set(sett.getMap(""))
//                    val metas = Kv.by("rootRoute", "sutra")
//                            .set("rootRouteUpName", "Sutra")
//                            .set("rootRouteLowName", "sutra")
//                            .set("configName", "JxtproConfig")
//                            .set("projectName", gmodel.projectName.value)
//                            .set("projectFilterName", StrKit.firstCharToUpperCase(gmodel.projectName.value))
//                            .set("projectFilterLowName", StrKit.firstCharToLowerCase(gmodel.projectName.value))
//                            .set("projectPackage", gmodel.projectPackage.value)
//                            .set("baseSrcPath", gmodel.baseSrcPath.value)
//                            .set("baseResourcesPath", gmodel.baseResourcesPath.value)
//                            .set("baseWebAppPath", gmodel.baseWebAppPath.value)
//                            .set("baseWEBINFPath", gmodel.baseWEBINFPath.value)
//                            .set("db_dev_dbType", "mysql")
//                            .set("db_dev_jdbcUrl", "jdbc:mysql://localhost/aiopms?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false")
//                            .set("db_dev_user", "root")
//                            .set("db_dev_password", "root")
//                            .set("db_dev_devMode", "true")
//                            .set("db_pro_dbType", "mysql")
//                            .set("db_pro_jdbcUrl", "jdbc:mysql://localhost/aiopms?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false")
//                            .set("db_pro_user", "root")
//                            .set("db_pro_password", "root")
//                            .set("useShiro", "true")
//                            .set("useCron4j", "true")
//                            .set("usej2cache", "true")
//                            .set("useSelect", "true")
//                            .set("useZtree", "true")
//                            .set("useMode", "m2c")
//
//                    gen.build(metas)
////                    gen.build(kv)
//                    fire(GenEvent("generate success! "))
//                    Constants.closeDb(gmodel.dataSource.value)
//                } catch (e: Exception) {
//                    fire(GenEvent("generate failure" + e.toString()))
//                    Constants.closeDb(gmodel.dataSource.value)
//                }
//            }
                                }
                            }

                        }


                        field("数据库") {
                            combobox(gmodel.dbname, gmodel.dbs) {
                                selectionModel.selectedItemProperty().addListener { _, _, _ ->
                                    (if (!selectionModel.selectedItem.isNullOrEmpty()) {
                                        genSrv.prapare()
                                        gmodel.tableCounts.value = "当前数据库中共有${gmodel.tables.size.toString()}张表"
                                    })
                                }
                            }
                        }
                        field("数据表") {
                            combobox(gmodel.leftTable, gmodel.tables)
                            {
                                selectionModel.selectedItemProperty().addListener { _, _, _ ->
                                    (if (!selectionModel.selectedItem.isNullOrEmpty()) {
//                                    genSrv.getColumns()
                                        gmodel.getColumnsSql.value = "select column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='${gmodel.dbname.value}' and TABLE_NAME='${gmodel.leftTable.value}'"
                                        gmodel.columns.addAll(genSrv.getList(gmodel.dataSource.value.connection, gmodel.getColumnsSql.value))
                                    })
                                }
                            }
                        }
                        field("表字段") {
                            combobox(gmodel.column, gmodel.columns)
                        }
                        field("查寻") {
                            combobox(gmodel.column, gmodel.columns)
                        }
                    }
                }
            }
//        label("HOST:")
//        textfield(gmodel.host) {
//            addClass(Styles.txt100)
//            text = "localhost"
//            required(message = "Enter host for your database")
//        }
//        label("PORT:")
//        textfield(gmodel.port) {
//            addClass(Styles.txt100)
//            text = "3306"
//            filterInput(FirstTenFilter)
//            required(message = "Enter port for your database")
//        }
//        label("USER:")
//        textfield(gmodel.user) {
//            addClass(Styles.txt100)
//            text = "root"
//            required(message = "Enter user name for your database")
//        }
//        label("PWD:")
//        textfield(gmodel.pwd) {
//            addClass(Styles.txt100)
//            text = "root"
//            required(message = "Enter user name for your database")
//        }
//        button("测试连接") {
//            action {
//                if ((gmodel.arp.value!= null)) {
////                    Constants.closeDb(gmodel.dataSource.value)
//                    gmodel.arp.value.stop()
//                }
//                // 每次点击"测试连接"测试连接时，都将之前保存的db和table列表清空
//                gmodel.dbs.clear()
//                gmodel.tables.clear()
//                if (testDb2().not()) return@action
//            }
//        }
//        combobox(gmodel.dbname, gmodel.dbs){
//            selectionModel.selectedItemProperty().addListener { _, _, _ ->
//                (if (!selectionModel.selectedItem.isNullOrEmpty()) {
//                    genSrv.prapare()
//                })
//            }
//        }
//        combobox(gmodel.leftTable, gmodel.tables)


        }
    }


    /**
     * test connection for postgresql, mysql,oracle,sqlserver
     */
    fun testDb2(): Boolean {
        try {
            genSrv.getCon()
            gmodel.dbOK.value = true
            genSrv.getDBs()
            fire(GenEvent("恭喜！数据库连接成功！"))
            return true
        } catch (e: Exception) {
            gmodel.dbOK.value = false
            fire(GenEvent("testDb() test connection failed: $e"))
            return false
        }
    }
}

